#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <cstdlib>

using namespace std;

int m,n;

typedef struct TPoint {
	int x, y;
} TPoint;

typedef struct TCell {
	int v;
	vector<TPoint> formula;
	bool caled;
} TCell;


TPoint tPoint(char *x) {
	TPoint t;
	int v=0;
	for (int i=0; i<strlen(x); ++i)
		if ('A' <= x[i] && x[i] <='Z') {
			v=v*26+x[i]-'A'+1;
		}
		else {
			t.y = v-1;
			t.x = atoi(&x[i])-1;
			break;
		}
	return t;
}

TCell **sheet;
vector<int> formulaList;
vector<int> newFl;

int main(void)
{
	int testcases;
	cin >> testcases;
	char str[100];

	bool firstBlood = true;
	for (int testi=0; testi<testcases; ++testi) {
		formulaList.clear();
		cin >> n >> m;
		sheet = new TCell *[m];
		for (int i=0; i<m; ++i) {
			sheet[i] = new TCell[n];
			for (int j=0; j<n; ++j) {
				sheet[i][j].formula.clear();
				cin >> str;
				if (str[0] == '=') {
					sheet[i][j].caled =false;
					char *ptr;
					ptr = strtok(str+1, "+");
					sheet[i][j].formula.push_back(tPoint(ptr));

					while (true) {
						ptr = strtok(NULL, "+");
						if (ptr == NULL) break;
						sheet[i][j].formula.push_back(tPoint(ptr));
					}


					formulaList.push_back(i*n+j);
				}
				else {
					sheet[i][j].caled = true;
					sheet[i][j].v = atoi(str);
				}
			}
		}

		while (formulaList.size()>0) {
			newFl.clear();
			for (unsigned int i=0; i<formulaList.size(); ++i) {
				int a, b;
				a = formulaList[i] / n;
				b = formulaList[i] % n;
// 				cout << a << " " << b << endl;
				int v = 0;
				bool caled = true;
				for (unsigned int j=0; j<sheet[a][b].formula.size(); ++j) {
					TPoint t = sheet[a][b].formula[j];
// 					cout << t.x << " " << t.y << endl;
					if (sheet[t.x][t.y].caled) v+=sheet[t.x][t.y].v;
					else {
						newFl.push_back(formulaList[i]);
						caled = false;
						break;
					}
				}
				if (caled) {
					sheet[a][b].caled = true;
					sheet[a][b].v = v;
				}
			}
			formulaList.clear();
			for (unsigned int i=0; i<newFl.size(); ++i)
				formulaList.push_back(newFl[i]);
		}
		
// 		if (!firstBlood) cout << endl;
// 		else firstBlood = false;

		for (int i=0; i<m; ++i) {
			for (int j=0; j<n; ++j) {
				cout << sheet[i][j].v;
				if (j<n-1) cout << " ";

			}
			cout << endl;
		}

		

	}
	return 0;
}